package com.example.cloudinterviewdemo;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liuwanxu
 * @date 2025/8/28 14:39
 */
@RestController
public class MetaspaceStressController {
    private List<Class<?>> classList = new ArrayList<>();

    /**
     * 模拟元空间内存溢出
     */
    @GetMapping("/memory/metaspace")
    public String stressMetaspace() {
        for (int i = 0; i < 1000; i++) {
            Enhancer enhancer = new Enhancer();
            enhancer.setSuperclass(Object.class);
            enhancer.setUseCache(false); // 关键：禁用缓存，让每个类都是新的
            enhancer.setCallback((MethodInterceptor) (obj, method, args, proxy) -> proxy.invokeSuper(obj, args));

            // 动态创建并加载类
            Class<?> clazz = enhancer.createClass();
            classList.add(clazz);
        }
        return "Generated " + classList.size() + " classes.";
    }
}
